#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2019 crane <crane@gosun>
#
# Distributed under terms of the MIT license.

"""

"""


def proceed(num, row, col):
    row_up = num
    row_down = row - row_up - 1

    if row_up > row_down :
        return False

    col_left = num
    col_right = col - col_left - 1
    if col_left > col_right:
        return False

    return True

def row_up(res, num, row, col, mat):
    # 整行, 包括两边的边界
    row_up = num
    col_left = num
    col_right = col - col_left - 1

    for i in range(col_left, col_right+1):
        res.append( mat[row_up][i] )

def col_right(res, num, row, col, mat):
    # 两行中间夹着的列, 不包括上下边界
    col_right = col - num - 1

    row_up = num
    row_down = row - row_up - 1

    for i in range(row_up+1, row_down):
        res.append( mat[i][col_right] )

def row_down(res, num, row, col, mat):
    # 整行, 包括边界
    row_up = num
    row_down = row - num - 1

    if row_up == row_down:
        # row_up已经处理过, 不要重复处理
        return

    col_left = num
    col_right = col - col_left - 1

    for i in range(col_right, col_left-1, -1):
        res.append( mat[row_down][i] )

def col_left(res, num, row, col, mat):
    # 两行中间夹着的列, 不包括上下边界
    col_left = num
    col_right = col - num - 1

    if col_left == col_right:
        # col_right中已经处理过了
        return

    row_up = num
    row_down = row - row_up - 1

    for i in range(row_down-1, row_up, -1):
        res.append( mat[i][col_left] )

def clockwise_snake(matrix):
    row, col = len(matrix), len(matrix[0])

    margin_num = 0

    res = []
    while proceed(margin_num, row, col):
        row_up(res, margin_num, row, col, matrix)
        col_right(res, margin_num, row, col, matrix)
        row_down(res, margin_num, row, col, matrix)
        col_left(res, margin_num, row, col, matrix)

        margin_num += 1

    return res


def test():
    l =  [1, 2, 3]
    l2 = [4, 5, 6]
    l3 = [7, 8, 9]
    l4 = ['a', 'b', 'c']
    l5 = ['d', 'e', 'f']

    # m = [l, l2, l3]
    m = [l, l2, l3, l4, l5]

    res = clockwise_snake(m)
    print(res)

    assert len(res) == len(m) * len(m[0])       # 测试

def main():
    print("start main")
    test()

if __name__ == "__main__":
    main()
